package com.dmm.vod.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.dmm.vod.entity.Subject;
import com.dmm.vod.service.SubjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ChenTaoTao
 * @Date: 2022/3/28 12:25
 * @Describe:
 */
@Slf4j
public class AccountImportListener extends AnalysisEventListener<Subject> {

    private static final int BATCH_COUNT = 1000;

    List<Subject> data = new ArrayList<>();

    SubjectService accountService;

    public AccountImportListener(SubjectService accountService){
        this.accountService = accountService;
    }

    /**
     *  读数据的过程中要做什么,如设置默认值等等
     */
    @Override
    public void invoke(Subject account, AnalysisContext analysisContext) {
        log.info("被添加的数据为i{}",account);
        data.add(account);
        if(data.size()==BATCH_COUNT){
            accountService.saveBatch(data);
            data.clear();
        }
    }

    /**
     * 所有数据读完以后要做什么
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        if(!CollectionUtils.isEmpty(data)){
            accountService.saveBatch(data);
            data.clear();
        }
        log.info("恭喜,数据已经导入成功啦!");
    }
}

